// server.js
const express = require('express');
const expressWs = require('express-ws')

const http = require('http');
const WebSocket = require('ws');
const cors = require('cors');

const app = express();
expressWs(app);

const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

const clients = new Map();

app.use(cors());

// 静态文件服务
app.use(express.static('public'));

// WebSocket 路由
app.ws('/ws', (ws, req) => {
  ws.on('message', (message) => {
    console.log('Received message:', message);
    sendFn(ws, 'Pong');
  });

  ws.on('close', () => {
    console.log('WebSocket connection closed');
  });

  ws.on('error', (error) => {
    console.error('WebSocket error:', error);
  });

  // ws.on('pong', function onPong () {
  //   console.log('Pong received');
  // });
  // const interval = setInterval(() => {
  //   if (ws.readyState === WebSocket.OPEN) {
  //     ws.ping();
  //   }
  // }, 30000);
});

// HTTP 路由
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/public/index.html');
});

wss.on('connection', function connection (ws) {
  console.log('ws.readyState', ws.readyState);
  console.log('ws.url', ws.url);
  console.log('ws.protocol', ws.protocol);
  console.log('ws.extensions', ws.extensions);
  console.log('ws.isConnected', ws.isConnected);
  ws.on('message', function incoming (res) {
    const data = JSON.parse(res)
    const id = data.uuid
    console.log('收到前端发来的信息:', data);
    clients.set(id, ws);
    console.log('clients=', clients);
    if (data.type) {
      broadcastMessage('服务器：' + data.msg, data.type)
    }
  });

  sendFn(ws, 'wss已连接');
});

setInterval(() => {
  broadcastMessage('wss定时询问，你还在监听吗？')
}, 5000);

// 向所有客户端发送消息的函数
function broadcastMessage (message, type) {
  console.log('wss.clients', wss.clients);
  wss.clients.forEach(function each (client) {
    console.log('client.id=', client.id);
    console.log('client=', client);
    if (client.readyState === WebSocket.OPEN) {
      sendFn(client, message, type);
    }
  });
}

// 向客户端发送消息
// type: 0.系统消息 1.清除客户端日志 2.f5刷新客户端
function sendFn (ws, msg, type) {
  const data = {
    msg: msg,
    type: type || 0,
    uuid: ws.id
  }
  ws.send(JSON.stringify(data));
}

server.listen(8081, () => {
  console.log('WebSocket server is running on ws://localhost:8081');
});